<?php
// запуск

// disable direct run
if( sizeof( get_included_files() ) < 2 ) {
    exit("Yea! Bud you bad hacker");
}

error_reporting(E_ALL);

global $tenders;
$tenders = array();
$tenders['conf'] = array();
$conf = &$tenders['conf'];

require_once dirname(__FILE__) . "/config.php";
include_once dirname(__FILE__) . "/../config.rw.php";

if ( !defined('ADODB_ERROR_HANDLER_TYPE') ) {
    define('ADODB_ERROR_HANDLER_TYPE', E_USER_NOTICE );
}

require_once $conf['libdir'] . '/p_php.php';
require_once $conf['libdir'] . '/adodb5/adodb.inc.php';
require_once $conf['libdir'] . '/adodb5/adodb-exceptions.inc.php';
require_once $conf['libdir'] . '/adodb5/adodb-active-record.inc.php';
require_once $conf['libdir'] . '/smarty/Smarty.class.php';

require_once $conf['libdir'] . '/kode_memcache_smarty_cache.inc.php';

include_once $conf['libdir'] . '/generate_rtf.php';
include_once $conf['libdir'] . '/util_str2.php';

// Подключение ко второй БД
$person = ADONewConnection( $conf['db_conf']['person']['dsn'] .'?new');
$person->debug=$conf['db_conf']['person']['debug'];
$person->Execute('set names utf8');
$conf['dbs']['person'] = &$person;

// вынести в кониг
$memcache_obj = new Memcache;
$memcache_obj->connect('localhost', 11611);
$GLOBALS['memcached_res'] = &$memcache_obj;

$tenders['db'] = ADONewConnection( $conf['db_conf']['tenders']['dsn'] . '?new');
$tenders['db']->debug = $conf['db_conf']['tenders']['debug'] ;
$tenders['db']->Execute('set names utf8');

$conf['dbs']['tenders'] = &$tenders['db'];

ADOdb_Active_Record::SetDatabaseAdapter($tenders['db']);

class item extends ADOdb_Active_Record {
    var $_table = 'item';
    var $item_id;
    var $item_id_internal;
    var $name;
    var $site_id;
    var $type_id_dict;
    var $status_id_dict;

    var $date_publication; // дата публикации
    var $date_end; // дата окончания
    var $date_conf; // дата заседания
}

require_once dirname(__FILE__) . "/tenders_action.php";
require_once dirname(__FILE__) . "/tenders_model.php";


function multitender_autoload($class) {
    $conf = &$GLOBALS['tenders']['conf'];
    if (preg_match('/multitender_action_([\w_]+)/i', $class, $m)) {
        $file = $conf['dir']['action'] . '/' . $m[1] . '.action.php';
        if (is_file($file)) {
            require_once $file;
        }
    }
    if (preg_match('/multitender_model_([\w_]+)/i', $class, $m)) {
        $file = $conf['dir']['model']  . '/' . $m[1] . '.model.php';
        if (is_file($file)) {
            require_once $file;
        }
    }
}

if ( is_callable('__autoload') ) {
    spl_autoload_register('__autoload');
}
spl_autoload_register('multitender_autoload');

function tenders_run_action($action) {
    return tenders_new_action($action)->run();
}

function tenders_new_action($action) {
    $class = 'multitender_action_' . $action;
    return new $class;
}

// rename to org.tender-consalt.new

function tenders_new_model($name) {
    $class = 'multitender_model_' . $name;
    if ( method_exists($class, 'singleton') ) {
        $obj = call_user_func(array($class, 'singleton'));
        // $obj = $class::singleton(); // dont work
    } else {
        $obj = new $class;
    }
    return $obj;
}

function tenders_generate_url_default($action) {
    return "some_url";
}

function tc_ajax_solt($uid) {
    $hash = md5(md5(AJAX_SOLT.$uid));
    return substr($hash, 0, 16);
}

function tc_try_set_bots() {   
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        return false;
    }
    // Блокировка парсера
    if (stripos($_SERVER['HTTP_USER_AGENT'], 'Synapse') !== FALSE) {
        header("HTTP/1.0 403 Forbidden");
        die ("Bots are not allowed");
    }
    // Костыль, браузеры клиентов от ПС определялись как боты
    if (stripos($_SERVER['HTTP_USER_AGENT'], 'Yandex Browser') !== FALSE) {
        return FALSE;
    }
    if (stripos($_SERVER['HTTP_USER_AGENT'], 'Windows') !== FALSE) {
        return FALSE;
    }

    if (stripos($_SERVER['HTTP_USER_AGENT'], 'Linux') !== FALSE) {
        return FALSE;
    }
    $bots = array(
            'Yandex'                => array('name'=>'YandexBot',   'id'=>'21'),
            'StackRambler'          => array('name'=>'RamblerBot',  'id'=>'22'),
            'GoogleBot'             => array('name'=>'GoogleBot',   'id'=>'23'),
            'Mediapartners-Google'  => array('name'=>'GoogleBot',   'id'=>'23'),
            'Adsbot-Google'         => array('name'=>'GoogleBot',   'id'=>'23'),
            'Yahoo'                 => array('name'=>'Yahoo',       'id'=>'24'),
            'MSNBot'                => array('name'=>'MSNBot',      'id'=>'25'),
    );
    
    foreach ($as as $s => $bot) {
        if(preg_match("/$s/i", $_SERVER['HTTP_USER_AGENT'])) {
            $GLOBALS['tenders']['conf']['user']['id']    = $bot['id'];
            $GLOBALS['tenders']['conf']['user']['name']  = $bot['name'];
            $GLOBALS['tenders']['conf']['user']['type'] = 'bot';
            return true;
        }
    }
}


/**
 *
 * @param string $word слово в им. падеже
 * @param int $count количество
 */
function factor($word, $count) {
    $words = array(
        'тендер' => array(
            1 => 'тендер',
            2 => 'тендера',
            5 => 'тендеров',
        ),
    );
    if (!array_key_exists($word, $words)) {
        return $word;
    }
    $count = $count % 100;
    if ($count>=10 && $count <=20) {
        $count = 5;
    } else {
        $count = $count % 10;
        if ($count == 1) {
            $count = 1;
        } else if ($count>=2 && $count<=4) {
            $count = 2;
        } else {
            $count = 5;
        }
    }

    return $words[$word][$count];
}
